import React, {Component} from 'react'
import {
    PlusOutlined
} from '@ant-design/icons'
import Pagination from '@/components/common/Pagination'
import AddProduct from '@/components/common/AddProduct'
// getProductsList
import { getProductsList } from '../../api/products'
import './css/productList.scss'
export default class Layout extends Component {
    componentDidMount() {
        this.getProductsList()
    }
    state = {
        list: [],
        childRef: null,
        curIndex: null
    }
    handleLi = (el, index) => {
        const { childRef } = this.state
        this.setState({curIndex: index})
        childRef.openModal(el)
    }
    getProductsList = () => {
        getProductsList().then(res => {
            const { list } = res
            list.forEach(el => {
                el.imgUrls = [el.productImg]
            })
            this.setState({ list })
        })
    }
    handleChildEvent = (ref) => {
        this.state.childRef = ref
    }
    render() {
        return (
            <div>
                <ul className={'productList'}>
                    {
                        this.state.list.map((el, index) => {
                            return <li key={index} onClick={() => this.handleLi(el, index)}>
                                      <div className={'img-box'}>
                                          <img alt={`${index}tp`} src={`${window.CONFIG.baseURL}/${el.productImg}`}/>
                                      </div>
                                      <div className="title">{el.productName}</div>
                                   </li>
                        })
                    }
                    <li style={{cursor: 'pointer'}} onClick={() => this.handleLi('add')}>
                        <PlusOutlined style={{fontSize: '20px'}} />
                    </li>
                </ul>
                <Pagination />
                <AddProduct info={
                    {
                        callback: data => {
                            const { list, curIndex } = this.state
                            if (curIndex) {
                                for (const k in data) {
                                    list[curIndex][k] = data[k]
                                }
                            } else {
                                list.push(data)
                            }
                            this.setState({list, curIndex: null})
                        }
                    }
                } onChildEvent={this.handleChildEvent} />
            </div>
        )
    }
}
